/***********************************************
 This file is part of redia-lib-utils-ios
 
 
 Copyright (c) 2015 Redia A/S
 
 Redia-library-app-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-library-app-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-library-app-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

#import "UIColor+HTML.h"

@implementation UIColor (HTML)

- (NSString*)toHTMLColorString
{
    CGFloat r, g, b, a;
    if ([self getRed:&r green:&g blue:&b alpha:&a]) {
        return [NSString stringWithFormat:@"#%2.2X%2.2X%2.2X", (int)(255 * r), (int)(255 * g), (int)(255 * b)];
    }
    else {
        // We are not in the rgb color space. Try white color space instead!
        CGFloat w;
        if ([self getWhite:&w alpha:&a]) {
            int value = (int)(255 * w);
            return [NSString stringWithFormat:@"#%2.2X%2.2X%2.2X", value, value, value];
        }
        return nil;
    }
}

+ (UIColor*)colorWithHTMLColor:(NSString*)htmlColor
{
    if (htmlColor==nil) {
        return nil;
    }
    
    NSScanner *scanner = [NSScanner scannerWithString:htmlColor];
    [scanner setScanLocation:1];
    unsigned int value;
    if ([scanner scanHexInt:&value]) {
        int r = value >> 16;
        int g = (value & 0x00FF00) >> 8;
        int b = value & 0x0000FF;
        return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0];
    }
    return nil;
}

@end
